import { ListGroup, ListState } from "../../dto/listDto";
import {confirm, page, ReservationDto} from "../../api/reservation";
import { UserDto } from "../../api/user";
import { LENGYU_SUCCESS_CODE } from "../../utils/request";

// pages/list/list.ts
Page({
  data: {
    state: {
      groups: [],
      loading: false,
      refreshing: false,
      hasMore: true,
      page: 1,
      pageSize: 5,
      activeGroup: 0
    } as ListState,
    activeGroup:{} as ListGroup,
    user:{} as UserDto
  },

  onLoad() {
    this.init();
    this.initData();
    this.loadList();
  },

  // 初始化分组数据
  initData() {
    const groups: ListGroup[] = [
      { key: 0, title: '待确认', count: 0, list: [] ,hasMore:true},
      { key: 1, title: '已通过', count: 0, list: [] ,hasMore:true},
      { key: 2, title: '已拒绝', count: 0, list: [] ,hasMore:true},
      { key: 3, title: '已取消', count: 0, list: [] ,hasMore:true}
    ];

    this.setData({
      'state.groups': groups
    });

  },
  init(){
    let userStr =  wx.getStorageSync("user");
    let user1:UserDto = JSON.parse(userStr) as UserDto
    this.setData({
      "user":user1
    })
  },
  // 获取当前激活分组的列表
  getCurrentGroupList() {
    const { groups, activeGroup } = this.data.state;
    const currentGroup = groups.find(group => group.key === activeGroup);
    console.log("当前分组信息",currentGroup)
    this.setData({
      'activeGroup':currentGroup,
      'state.hasMore':currentGroup?currentGroup.hasMore:true
    })
  },

  // 切换分组
  switchGroup(e: any) {
    const groupKey = e.currentTarget.dataset.group;
    
    this.setData({
      'state.activeGroup': groupKey,
      'state.page': 1,
      'state.hasMore': true
    });

    // 如果当前分组没有数据，则加载
    this.getCurrentGroupList()
    console.log("切换tab之后的信息",this.data.activeGroup)
    if (this.data.activeGroup && this.data.activeGroup.list.length === 0) {
      this.loadList();
    }
  },

  // 加载列表数据
  async loadList() {
    if (this.data.state.loading || (!this.data.state.hasMore && !this.data.state.refreshing)) {
      return;
    }
    this.setData({
      'state.loading': true
    });

    try {
  
      let result = await page(this.data.state.activeGroup,this.data.state.page,this.data.state.pageSize)
      console.log("清单列表",result)
      this.updateGroupList(result.data.records);
    
      this.setData({
        'state.hasMore': result.data.records.length >= this.data.state.pageSize,
        'state.page': this.data.state.page + 1,
        'state.loading': false,
        'state.refreshing': false
      });


    } catch (error) {
      console.error('加载列表失败:', error);
      this.setData({
        'state.loading': false,
        'state.refreshing': false
      });
    }
  },

  // 更新分组列表数据
  updateGroupList(newList: ReservationDto[]) {
    const { groups } = this.data.state;
    
    // 按分组重新组织数据
    const groupedData: { [key: string]: ReservationDto[] } = {};
    groups.forEach(group => {
      groupedData[group.key] = newList.filter(item => item.status === group.key);
    });

    // 更新各组数据和计数
    const updatedGroups = groups.map(group => ({
      ...group,
      list: group.key === this.data.state.activeGroup ? 
            [...group.list, ...groupedData[group.key]] : 
            group.list,
      count: group.list.length + groupedData[group.key].length,
      hasMore: group.key === this.data.state.activeGroup ? groupedData[group.key].length >= this.data.state.pageSize : group.hasMore
    }));

    this.setData({
      'state.groups': updatedGroups
    });
    this.getCurrentGroupList()
    console.log(this.data.state)
  },

  // 下拉刷新
  onRefresh() {
    this.setData({
      'state.refreshing': true,
      'state.page': 1,
      'state.hasMore': true
    });

    // 清空当前分组数据
    const { groups, activeGroup } = this.data.state;
    const updatedGroups = groups.map(group => 
      group.key === activeGroup ? { ...group, list: [], count: 0 } : group
    );

    this.setData({
      'state.groups': updatedGroups
    });

    this.loadList();
  },

  // 上拉加载更多
  onLoadMore() {
    this.loadList();
  },




  // 状态文本映射
  getStatusText(status: number): string {
    const statusMap: { [key: number]: string } = {
      0: '待确认',
      1: '已通过', 
      2: '已拒绝',
      3: '已取消'
    };
    return statusMap[status] || "未知";
  },

  // 操作处理
  async onConfirm(e: any) {
    const id = e.currentTarget.dataset.id;
    const status = e.currentTarget.dataset.status;
    console.log("同意申请：" ,id,status)
    let res = await confirm(id,status);
    if(res.code == LENGYU_SUCCESS_CODE){
      this.onRefresh()
    }
    else{
      wx.showToast({
        title: '删除成功',
        icon: 'error'
      });
    }
  },



 

  // 删除项目
  removeItem(id: string) {
    const { groups } = this.data.state;
    
    const updatedGroups = groups.map(group => ({
      ...group,
      list: group.list.filter(item => item.id !== id),
      count: group.list.filter(item => item.id !== id).length
    }));

    this.setData({
      'state.groups': updatedGroups
    });

    wx.showToast({
      title: '删除成功',
      icon: 'success'
    });
  },

  // 添加新项目
  onAddItem() {
    wx.navigateTo({
      url: '/pages/add/add'
    });
  },

});